package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.constant.MessageConstant;
import com.itheima.entity.Result;
import com.itheima.service.MemberService;
import com.itheima.service.OrderService;
import com.itheima.service.ReportService;
import net.sf.jasperreports.engine.JasperCompileManager;
import net.sf.jasperreports.engine.JasperExportManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.InputStream;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;


@RestController
@RequestMapping("/report")
public class ReportController {
    @Reference
    private MemberService memberService;
    @Reference
    private OrderService orderService;
    @Reference
    private ReportService reportService;

    //会员数量折线图数据
    @RequestMapping("/getMemberReport")
    public Result getMemberReport() {
        try {
            Map<String, Object> map = new HashMap<String, Object>();
            List<String> months = new ArrayList<>();
            //获取当前时间
            Calendar calendar = Calendar.getInstance();
            //计算过去一年12月时间
            calendar.add(Calendar.MONTH, -12);//获得当前时间往前推12个月的时间
            for (int i = 0; i < 12; i++) {
                //获得当前时间往后推一个月日期
                calendar.add(calendar.MONTH, 1);
                months.add(new SimpleDateFormat("yyyy.MM").format(calendar.getTime()));
            }
            map.put("months", months);
            //获取会员人数
            List<Integer> memberCount = memberService.findMemberCountByMonths(months);
            map.put("memberCount", memberCount);
            return new Result(true, MessageConstant.GET_MEMBER_NUMBER_REPORT_SUCCESS, map);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.GET_MEMBER_NUMBER_REPORT_FAIL);
        }
    }

    //会员饼状图数据
    @RequestMapping("/getSetmealReport")
    public Result getSetmealReport() {
        //使用模拟数据测试使用什么样的java对象转为饼形图所需的json数据格式
        try {
            List<Map<String, Object>> list = orderService.findBySetmealCount();
            return new Result(true, MessageConstant.GET_SETMEAL_COUNT_REPORT_SUCCESS, list);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(true, MessageConstant.GET_SETMEAL_COUNT_REPORT_FAIL);
        }

    }

    //运营数据统计
    @RequestMapping("/getBusinessReportData")
    public Result getBusinessReportData() {
        try {
            Map<String, Object> data = reportService.getBusinessReportData();
            return new Result(true, MessageConstant.GET_BUSINESS_REPORT_SUCCESS, data);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.GET_BUSINESS_REPORT_FAIL);
        }
    }
    //导出运行数据统计Excel表
    @RequestMapping("/exportBusinessReport")
    public Result exportBusinessReport(HttpServletRequest request, HttpServletResponse response){
        try {
            Map<String, Object> result = reportService.getBusinessReportData();
            //取出返回结果数据，准备将报表数据写入到Excel文件中
            String reportDate = (String) result.get("reportDate");
            Integer todayNewMember = (Integer) result.get("todayNewMember");
            Integer totalMember = (Integer) result.get("totalMember");
            Integer thisWeekNewMember = (Integer) result.get("thisWeekNewMember");
            Integer thisMonthNewMember = (Integer) result.get("thisMonthNewMember");
            Integer todayOrderNumber = (Integer) result.get("todayOrderNumber");
            Integer thisWeekOrderNumber = (Integer) result.get("thisWeekOrderNumber");
            Integer thisMonthOrderNumber = (Integer) result.get("thisMonthOrderNumber");
            Integer todayVisitsNumber = (Integer) result.get("todayVisitsNumber");
            Integer thisWeekVisitsNumber = (Integer) result.get("thisWeekVisitsNumber");
            Integer thisMonthVisitsNumber = (Integer) result.get("thisMonthVisitsNumber");
            List<Map<String, Object>> hotSetmeal = (List<Map<String, Object>>) result.get("hotSetmeal");
            //读取文件
            InputStream is = request.getSession().getServletContext().getResourceAsStream("/template/report_template.xlsx");
            //基于提供的Excel模板文件在内存中创建一个Excel表格对象
            XSSFWorkbook workbook = new XSSFWorkbook(is);
            //读取第一个工作表
            XSSFSheet sheetAt = workbook.getSheetAt(0);
            //在相应位置写入相应数据
            //写入报表时间
            XSSFRow row = sheetAt.getRow(2);//日期
            XSSFCell cell = row.getCell(5);
            cell.setCellValue(reportDate);
            //写入新增会员数
             row = sheetAt.getRow(4);
             cell=row.getCell(5);
             cell.setCellValue(todayNewMember);
             //写入总会员数
            row=sheetAt.getRow(4);
            cell=row.getCell(7);
            cell. setCellValue(totalMember);
            //写入本周新增会员数
            row=sheetAt.getRow(5);
            cell=row.getCell(5);
            cell.setCellValue(thisWeekNewMember);
            //写入本月新增会员数
            row=sheetAt.getRow(5);
            cell=row.getCell(7);
            cell.setCellValue(thisMonthNewMember);
            //写入今日预约数
            row=sheetAt.getRow(7);
            cell=row.getCell(5);
            cell.setCellValue(todayOrderNumber);
            //写入今日到诊数
            row=sheetAt.getRow(7);
            cell=row.getCell(7);
            cell.setCellValue(todayVisitsNumber);
            //写入本周预约数
            row=sheetAt.getRow(8);
            cell=row.getCell(5);
            cell.setCellValue(thisWeekOrderNumber);
            //写入本周到诊数
            row=sheetAt.getRow(8);
            cell=row.getCell(7);
            cell.setCellValue(thisWeekVisitsNumber);
            //写入本月预约数
            row=sheetAt.getRow(9);
            cell=row.getCell(5);
            cell.setCellValue(thisMonthOrderNumber);
            //写入本月到诊数
            row=sheetAt.getRow(9);
            cell=row.getCell(7);
            cell.setCellValue(thisMonthVisitsNumber);
            //写入入门套餐
            for (int i = 0; i < hotSetmeal.size(); i++) {
                row=sheetAt.getRow(12+i);
                Map<String, Object> map = hotSetmeal.get(i);
                row.getCell(4).setCellValue((String) map.get("name"));//套餐名称
                row.getCell(5).setCellValue((Long)map.get("setmeal_count"));//预约数量
                row.getCell(6).setCellValue(((BigDecimal) map.get("proportion")).doubleValue());//套餐占比
            }
            //输出到浏览器 获取响应输出流
            OutputStream os = response.getOutputStream();
            //设置响应头???
            response.setHeader("content-Disposition","attachment;filename=report_template.xlsx");
            workbook.write(os);
            //释放资源
            os.close();
            is.close();
            workbook.close();
            return null;
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConstant.GET_BUSINESS_REPORT_FAIL);
        }

    }
    //导出运营数据到pdf并提供客户端下载
    @RequestMapping("/exportBusinessReport4PDF")
    public Result exportBusinessReport4PDF(HttpServletRequest request, HttpServletResponse response){
        try {
            Map<String, Object> result = reportService.getBusinessReportData();
            //取出返回结果数据，准备将报表数据写入到Excel文件中
            List<Map> hotSetmeal = (List<Map>) result.get("hotSetmeal");
            //动态获取模板文件绝对磁盘路径
            String jrxmlPath =
                    request.getSession().getServletContext().getRealPath("template") + File.separator + "health_business3.jrxml";
            String jasperPath =
                    request.getSession().getServletContext().getRealPath("template") + File.separator + "health_business3.jasper";
            //编译模板
            JasperCompileManager.compileReportToFile(jrxmlPath, jasperPath);
            JasperPrint jasperPrint = JasperFillManager.fillReport(jasperPath,result, new JRBeanCollectionDataSource(hotSetmeal));

            ServletOutputStream out = response.getOutputStream();
            response.setContentType("application/pdf"); response.setHeader("content-Disposition", "attachment;filename=report.pdf");
            //输出文件
            JasperExportManager.exportReportToPdfStream(jasperPrint,out);
            return null;
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConstant.GET_BUSINESS_REPORT_FAIL);

        }
    }

}
